package com.wxd.modules.function.controller;


import com.alibaba.fastjson.JSONArray;
import com.wxd.annotation.SysLog;
import com.wxd.modules.common.entity.*;
import com.wxd.modules.common.service.CauseService;
import com.wxd.modules.common.service.GenderService;
import com.wxd.modules.common.service.StatusService;
import com.wxd.modules.common.service.TypeService;
import com.wxd.modules.function.entity.*;
import com.wxd.modules.function.service.*;
import com.wxd.modules.sys.entity.SysDictEntity;
import com.wxd.modules.sys.service.SysDictService;
import com.wxd.utils.DbConnectUtil;
import com.wxd.utils.ExcelUtils;
import com.wxd.utils.PageUtils;
import com.wxd.utils.R;
import com.wxd.validator.ValidatorUtils;
import com.wxd.validator.group.AddGroup;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping("/fun/emp")
public class EmpController {
    @Autowired
    private EmpService empService;
    @Autowired
    private AddEmpService addEmpService;
    @Autowired
    private WorkExperienceService workExperienceService;
    @Autowired
    private RewardRecordService rewardRecordService;
    @Autowired
    private ChangeEmpDeptService changeEmpDeptService;
    @Autowired
    private ChangeEmpOfficeService changeEmpOfficeService;
    @Autowired
    private StatusChangeService statusChangeService;
    @Autowired
    private EmpStatusChangeService empStatusChangeService;
    @Autowired
    private GenderService genderService;
    @Autowired
    private CauseService causeService;
    @Autowired
    private StatusService statusService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private SwitchDataChangeService switchDataChangeService;
    @Autowired
    private HttpServletRequest request;

    /**
     * 在册员工列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("fun:emp:list")
    public R list(@RequestParam Map<String,Object> params)
    {
        PageUtils page = empService.queryPage(params);
        return R.ok().put("page",page);
    }
    /**
     * 统计员工列表
     */
    @RequestMapping("/statisticsList")
    @RequiresPermissions("fun:emp:list")
    public R statisticsList(@RequestParam Map<String,Object> params)
    {
        PageUtils page = empService.queryStatisticsPage(params);
        return R.ok().put("page",page);
    }
    /**
     * 字典列表
     */
    @RequestMapping("/dictList")
   /*  @RequiresPermissions("sys:dict:list")*/
    public R dictList(@RequestParam Map<String,Object> params)
    {
        List<SysDictEntity> sysDictEntities = sysDictService.queryOfficePage(params);
        return R.ok().put("dict",sysDictEntities);
    }
    /**
     * 在岗员工列表
     */
    @RequestMapping("/existList")
    @RequiresPermissions("fun:emp:list")
    public R existList(@RequestParam Map<String,Object> params)
    {
        PageUtils page = empService.queryPageExist(params);
        return R.ok().put("page",page);
    }
    /**
     * 不在岗员工列表
     */
    @RequestMapping("/notList")
    @RequiresPermissions("fun:emp:list")
    public R notList(@RequestParam Map<String,Object> params)
    {
        PageUtils page = empService.queryPageNot(params);
        return R.ok().put("page",page);
    }
    /**
     * 新进员工列表
     */
    @RequestMapping("/addList")
    @RequiresPermissions("fun:emp:list")
    public R addList(@RequestParam Map<String,Object> params)
    {
        PageUtils page = addEmpService.queryPage(params);
        return R.ok().put("page",page);
    }
    /**
     * 部门调动员工列表
     */
    @RequestMapping("/changeDeptList")
    @RequiresPermissions("fun:emp:list")
    public R changeDeptList(@RequestParam Map<String,Object> params)
    {
        PageUtils page = changeEmpDeptService.queryPage(params);
        return R.ok().put("page",page);
    }
    /**
     * 职名调动员工列表
     */
    @RequestMapping("/changeOfficeList")
    @RequiresPermissions("fun:emp:list")
    public R changeOfficeList(@RequestParam Map<String,Object> params)
    {
        PageUtils page = changeEmpOfficeService.queryPage(params);
        return R.ok().put("page",page);
    }
    /**
     * 不在册员工列表(减少的人员)
     */
    @RequestMapping("/changeStatusList")
    @RequiresPermissions("fun:emp:list")
    public R changeStatusList(@RequestParam Map<String,Object> params)
    {
        PageUtils page = statusChangeService.queryPage(params);
        return R.ok().put("page",page);
    }
    /**
     * 岗位变动记录
     */
    @RequestMapping("/empChangeStatusList")
    @RequiresPermissions("fun:emp:list")
    public R empChangeStatusList(@RequestParam Map<String,Object> params)
    {
        PageUtils page = empStatusChangeService.queryPage(params);
        return R.ok().put("page",page);
    }
    /*在岗变动记录*/
    @RequestMapping("/empChangeStatusExistList")
    @RequiresPermissions("fun:emp:list")
    public R empChangeStatusExistList(@RequestParam Map<String,Object> params)
    {
        PageUtils page = empStatusChangeService.queryNotLogPage(params);
        return R.ok().put("page",page);
    }
    /*不在岗变动记录*/
    @RequestMapping("/empChangeStatusNotList")
    @RequiresPermissions("fun:emp:list")
    public R empChangeStatusNotList(@RequestParam Map<String,Object> params)
    {
        PageUtils page = empStatusChangeService.queryExistLogPage(params);
        return R.ok().put("page",page);
    }
    /**
     * 基本信息
     */
    @RequestMapping("/info/{empId}")
    @RequiresPermissions("fun:emp:info")
    public R info(@PathVariable("empId")  Long empId)
    {
        String str=empService.queryParentDept(empId);

           switch(str)
            {
                case "jwd":
                {
                    return R.ok().put("emp", empService.queryAllJWDEmpById(empId));
                }
                case "kyd":
                {
                    return R.ok().put("emp", empService.queryAllKYDEmpById(empId));
                }
            }
        return R.ok();
    }
    /**
     * 新增信息
     */
    @RequestMapping("/infoAddEmp/{empId}")
    @RequiresPermissions("fun:emp:info")
    public R infoAddEmp(@PathVariable("empId")  Long empId)
    {
        AddEmp addEmp = addEmpService.queryAddEmp(empId);
        Type type = typeService.queryValue(addEmp.getJoinType());
        addEmp.setJoinTypeStr(type.getTypeValue());
        return R.ok().put("addEmp",addEmp);
    }
    /**
     * 部门变动信息
     */
    @RequestMapping("/infoChangeEmpDept/{empId}")
    @RequiresPermissions("fun:emp:info")
    public R infoChangeEmpDept(@PathVariable("empId")  Long empId)
    {
        List<EmpChangeDept> empChangeDept = changeEmpDeptService.queryChangeEmp(empId);
        return R.ok().put("changeEmpDept", empChangeDept);
    }
    /**
     * 职名变动信息
     */
    @RequestMapping("/infoChangeEmpOffice/{empId}")
    @RequiresPermissions("fun:emp:info")
    public R infoChangeEmpOffice(@PathVariable("empId")  Long empId)
    {
        List<EmpChangeOffice> empChangeOffice = changeEmpOfficeService.queryChangeEmp(empId);
        return R.ok().put("changeEmpOffice", empChangeOffice);
    }
    /**
     * 减少信息
     */
    @RequestMapping("/infoStatusChange/{empId}")
    @RequiresPermissions("fun:emp:info")
    public R infoStatusChange(@PathVariable("empId")  Long empId)
    {
        StatusChange statusChange = statusChangeService.queryStatusChange(empId);
        return R.ok().put("statusChange",statusChange);
    }
    /**
     * 岗位状态变动信息
     */
    @RequestMapping("/infoEmpStatusChange/{empId}")
    @RequiresPermissions("fun:emp:info")
    public R infoEmpStatusChange(@PathVariable("empId")  Long empId)
    {
        List<EmpStatusChange> empStatusChange = empStatusChangeService.queryEmpStatusChange(empId);
        for(EmpStatusChange emp:empStatusChange)
        {
            Status status = statusService.queryValue(emp.getStatus());
            Cause cause = causeService.queryValue(emp.getCause());
            emp.setCauseStr(cause.getCauseValue());
            emp.setStatusStr(status.getStatusValue());
        }
        return R.ok().put("empStatusChange",empStatusChange);
    }
    /**
     * 数据交换变动记录
     */
    @RequestMapping("/dataChangeList")
    @RequiresPermissions("fun:emp:list")
    public R dataChangeList(@RequestParam Map<String,Object> params)
    {
        PageUtils page = switchDataChangeService.queryPage(params);
        return R.ok().put("page",page);
    }
    /**
     * 工作信息
     */
    @RequestMapping("/work/{empId}")
    @RequiresPermissions("fun:emp:info")
    public R work(@PathVariable("empId")  Long empId)
    {
        List<WorkExperience> work = workExperienceService.queryWork(empId);
        return R.ok().put("work",work);
    }
    /**
     * 奖惩记录
     */
    @RequestMapping("/reward/{empId}")
    @RequiresPermissions("fun:emp:info")
    public R reward(@PathVariable("empId")  Long empId)
    {
        List<RewardRecord> reward = rewardRecordService.queryReward(empId);
        return R.ok().put("reward",reward);
    }
    /**
     * 保存
     */
    @SysLog("保存员工")
    @RequestMapping("/save")
    @RequiresPermissions("fun:emp:save")
    public R save(@RequestBody EmpEntity emp )
    {
        ValidatorUtils.validateEntity(emp, AddGroup.class);
        /*将添加的员工流程信息加入新进员工流程表*/
        addEmpService.saveAddEmp(emp);
        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改员工")
    @RequestMapping("/update")
    @RequiresPermissions("fun:emp:update")
    public R update(@RequestBody Map map){
        empService.updateEmp(map);
        return R.ok();
    }
    /**
     * 删除
     */
    @SysLog("删除员工")
    @RequestMapping("/delete")
    @RequiresPermissions("fun:emp:delete")
    public R delete(@RequestBody Long[] empIds)
    {
        empService.removeByIds(Arrays.asList(empIds));
        return R.ok();
    }
    /**
     * 调部门
     */
    @SysLog("调部门")
    @RequestMapping("/changeDept")
    @RequiresPermissions("fun:emp:changeDept")
    public R changeDept(@RequestBody ChangeDept emp){
        changeEmpDeptService.changeEmpty(emp);
        return R.ok();
    }
    /**
     * 变职名
     */
    @SysLog("调职名")
    @RequestMapping("/changeOffice")
    @RequiresPermissions("fun:emp:changeOffice")
    public R changeOffice(@RequestBody ChangeOffice emp){
        changeEmpOfficeService.changeEmpty(emp);
        return R.ok();
    }
    /*岗位状态变动上传的附件*/
    @SysLog("上传附件")
    @RequestMapping("/upLoad")
    public String nativeUpload(@RequestParam("file") MultipartFile file) {
        /*上传到本地Tomcat8服务器的power_design_attachment文件夹，服务器端口号为8080*/
        String path="F:\\apache-tomcat-8.5.61-windows-x64\\apache-tomcat-8.5.61\\webapps\\power_design_attachment";
        String filePath = path +"/"+ file.getOriginalFilename();
        File desFile = new File(filePath);
        if(!desFile.getParentFile().exists()){
            desFile.mkdirs();
        }
        try {
            file.transferTo(desFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "http://localhost:8080/power_design_attachment/"+file.getOriginalFilename();
    }
    /**
     * 员工状态改变在册变为不在册
     */
    @SysLog("在册状态")
    @RequestMapping("/changeStatus")
    @RequiresPermissions("fun:emp:update")
    public R changeStatus(@RequestBody ChangeStatus emp){
        statusChangeService.changeStatus(emp);
        return R.ok();
    }
    /**
     * 在岗与不在岗
     */
    @SysLog("岗位状态")
    @RequestMapping("/changeEmpStatus")
    @RequiresPermissions("fun:emp:update")
    public R changeEmpStatus(@RequestBody ChangeEmpStatus emp){
        empStatusChangeService.changeStatus(emp);
        return R.ok();
    }
    /**
     * 导出员工数据
     */
    @SysLog("导出员工表")
    @RequestMapping("/exportEmps")
    @RequiresPermissions("fun:emp:export")
    public void exportEmps(HttpServletResponse response,@RequestBody Long[] empIds ) throws IOException {
        List<EmpEntity> empList = empService.queryEmp(empIds);
        ExcelUtils.writeExcel(response, empList, EmpEntity.class);
    }
    /**
     * 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     *
     * @since 2.1.1
     */
    @SysLog("导出员工表")
    @RequestMapping("/exportEmp")
    @RequiresPermissions("fun:emp:export")
    public void exportEmp(HttpServletResponse response,@RequestBody Long[] empIds ) throws IOException {
        List<EmpEntity> empList = empService.queryEmp(empIds);
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
       /* try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String formatTime = sdf.format(d);
            String fileName = URLEncoder.encode("测试"+formatTime, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName +".xlsx");
            // 这里需要设置不关闭流
          EasyExcel.write(response.getOutputStream(), EmpEntity.class).autoCloseStream(Boolean.FALSE).sheet("模板")
                    .doWrite(empList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }*/
    }

    @SysLog("导入员工表")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @RequiresPermissions("fun:emp:import")
    @Transactional(rollbackFor = Exception.class)
    public R importExcel(@RequestParam(value="file", required = false) MultipartFile file){
      List<EmpEntity> list = ExcelUtils.readExcel("", EmpEntity.class, file);
        /*新进员工形成记录*/
       addEmpService.saveAddEmpList(list);
        return R.ok();
    }
    @SysLog("导入信息变化的人员表")
    @RequestMapping(value = "/importDataChangeExcel", method = RequestMethod.POST)
    @RequiresPermissions("fun:emp:import")
    @Transactional(rollbackFor = Exception.class)
    public R importDataChangeExcel(@RequestParam(value="file", required = false) MultipartFile file){
        List<EmpEntity> list = ExcelUtils.readExcel("", EmpEntity.class, file);
        /*更新人员变换的信息,表中生成的empId全局唯一*/
        switchDataChangeService.saveDataChangeEmpList(list);
        return R.ok();
    }
    /**
     * 编辑员工工作经历
     */
    @SysLog("编辑员工工作经历")
    @RequestMapping("/updateWork")
    @RequiresPermissions("fun:emp:save")
    public R updateWork(@RequestBody WorkExperience work){
        //校验类型
        ValidatorUtils.validateEntity(work);
        if(StringUtils.isNotBlank(work.getCompany())) {
            workExperienceService.save(work);
        }
        return R.ok();
    }
    /**
     * 编辑员工奖惩记录
     */
    @SysLog("编辑员工奖惩记录")
    @RequestMapping("/updateReward")
    @RequiresPermissions("fun:emp:save")
    public R updateReward(@RequestBody RewardRecord reward){
        //校验类型
        ValidatorUtils.validateEntity(reward);
        if(StringUtils.isNotBlank(reward.getName())) {
            rewardRecordService.save(reward);
        }
        return R.ok();
    }
    /*人员变动统计*/
    @RequestMapping("/changeStatisticsList")
    public R changeStatisticsList() {
        List<Map> addEmpListByMonth = addEmpService.addEmpStatisticsByMonth(new HashMap<String,Object>());
        List<Map> changeDeptListByMonth = changeEmpDeptService.changeDeptStatisticsByMonth(new HashMap<String,Object>());
        List<Map> changeOfficeListByMonth = changeEmpOfficeService.changeOfficeStatisticsByMonth(new HashMap<String,Object>());
        List<Map> removeEmpListByMonth = statusChangeService.removeEmpStatisticsByMonth(new HashMap<String,Object>());
        List<Map> changeNotStatusListByMonth = empStatusChangeService.changeNotStatusStatisticsByMonth(new HashMap<String,Object>());
        List<Map> changeExistStatusListByMonth = empStatusChangeService.changeExistStatusStatisticsByMonth(new HashMap<String,Object>());
        List<Map> list=new ArrayList<>();
        for(int i=0;i<12;i++)
        {
            Map map=new HashMap();
            map.put("month", addEmpListByMonth.get(i).get("month"));
            map.put("addEmp", addEmpListByMonth.get(i).get("num"));
            map.put("changeDept", changeDeptListByMonth.get(i).get("num"));
            map.put("changeOffice", changeOfficeListByMonth.get(i).get("num"));
            map.put("removeEmp", removeEmpListByMonth.get(i).get("num"));
            map.put("changeExistEmp", changeExistStatusListByMonth.get(i).get("num"));
            map.put("changeNotEmp", changeNotStatusListByMonth.get(i).get("num"));
            list.add(map);
        }
        return R.ok().put("list",list);
    }
    @RequestMapping("/addEmpStatistics")
    public R addEmpStatistics() {
        List<Map> addEmpListByMonth = addEmpService.addEmpStatisticsByMonth(new HashMap<String,Object>());

        return R.ok().put("addEmpListByMonth",addEmpListByMonth);
    }
    @RequestMapping("/changeDeptStatistics")
    public R changeDeptStatistics() {
        List<Map> changeDeptListByMonth = changeEmpDeptService.changeDeptStatisticsByMonth(new HashMap<String,Object>());

        return R.ok().put("changeDeptListByMonth",changeDeptListByMonth);
    }
    @RequestMapping("/changeOfficeStatistics")
    public R changeOfficeStatistics() {
        List<Map> changeOfficeListByMonth = changeEmpOfficeService.changeOfficeStatisticsByMonth(new HashMap<String,Object>());
        return R.ok().put("changeOfficeListByMonth",changeOfficeListByMonth);
    }

    @RequestMapping("/changeExistStatusStatistics")
    public R changeExistStatusStatistics() {
        List<Map> changeExistStatusListByMonth = empStatusChangeService.changeExistStatusStatisticsByMonth(new HashMap<String,Object>());
        return R.ok().put("changeExistStatusListByMonth",changeExistStatusListByMonth);
    }
    @RequestMapping("/changeNotStatusStatistics")
    public R changeNotStatusStatistics() {
        List<Map> changeNotStatusListByMonth = empStatusChangeService.changeNotStatusStatisticsByMonth(new HashMap<String,Object>());
        return R.ok().put("changeNotStatusListByMonth",changeNotStatusListByMonth);
    }

    @RequestMapping("/removeEmpStatistics")
    public R removeEmpStatistics() {
        List<Map> removeEmpListByMonth = statusChangeService.removeEmpStatisticsByMonth(new HashMap<String,Object>());
        return R.ok().put("removeEmpListByMonth",removeEmpListByMonth);
    }

    /*连接远程数据库*/
    @SysLog("连接远程数据库")
    @RequestMapping("/dbConnect")
    public R dbConnect(@RequestBody SaveDataToDb saveDataToDb) {
       ConnectDB connectDB=saveDataToDb.getConnectDB();
        ValidatorUtils.validateEntity(connectDB);
        return switchDataChangeService.saveEmpToDb(saveDataToDb);
    }

    /*将数据发送到消息队列*/
    @SysLog("保存到消息队列")
    @RequestMapping("/saveDataToMq")
    public R saveDataToMq(@RequestBody Long[] empIds) {

        return switchDataChangeService.saveEmpToMq(empIds);
    }
}